package com.oa.matter.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.matter.entity.MatterInfo;
import com.oa.matter.service.MatterInfoService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/**/oa/matter/matterInfo")
@Api(tags = {"事项库-事项基本信息-操作接口"})
public class MatterInfoController {

    static Logger logger = LoggerFactory.getLogger(MatterInfoController.class);

    @Autowired
    private MatterInfoService matterInfoService;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/uploadFile")
    public Result upLoadProduceImg(@RequestParam("file") MultipartFile file) {
        String fileName = new String();
        Map<String, Object> parseExcel = null;
        Tips tips = new Tips("上传成功");
        // 判断文件是否为空
        if (!file.isEmpty()) {
            InputStream fis = null;
            try {
                fis = file.getInputStream();
                parseExcel = matterInfoService.parseExcel(fis);
            } catch (BizException e) {
                // TODO: handle exception
                tips = e.getTips();
                logger.error(String.valueOf(e));
            } catch (Exception e) {
                logger.error(String.valueOf(e));
                tips.setErrMsg(e.toString());
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        }
        return Result.ok().setData(parseExcel).setTips(LangTips.fromTips(tips));
    }

    @ApiOperation(value = "事项库-事项基本信息-查询列表", notes = " ")
    @ApiEntityParams(MatterInfo.class)
    @ApiResponses({@ApiResponse(code = 200, response = MatterInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listMatterInfo(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        QueryWrapper<MatterInfo> qw = QueryTools.initQueryWrapper(MatterInfo.class, params);
        IPage page = QueryTools.initPage(params);

        List<Map<String, Object>> datas = matterInfoService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "导入数据", notes = "addMatterInfo,主键如果为空，后台自动生成")
    @ApiResponses({@ApiResponse(code = 200, response = MatterInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/importData", method = RequestMethod.POST)
    public Result importData(@RequestBody Map<String, Object> map) {


        matterInfoService.importData(map);

        return Result.ok();
    }


    @ApiOperation(value = "根据id查询事项信息", notes = "getMatterInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id,主键", required = true)})
    @ApiResponses({@ApiResponse(code = 200, response = MatterInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/getMatterInfo", method = RequestMethod.GET)
    public Result getMatterInfo(@RequestParam String id) {
        Map<String, Object> matterInfo = matterInfoService.getMatterInfo(null, null, id);

        return Result.ok().setData(matterInfo);
    }


    @ApiOperation(value = "事项库-事项基本信息-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MatterInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addMatterInfo(@RequestBody MatterInfo matterInfo) {


        matterInfo.setId(matterInfoService.createKey("id"));
        matterInfoService.insert(matterInfo);

        return Result.ok("add-ok", "添加成功！").setData(matterInfo);
    }

    @ApiOperation(value = "事项库-事项基本信息-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delMatterInfo(@RequestBody MatterInfo matterInfo) {


        matterInfoService.deleteByPk(matterInfo);

        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "事项库-事项基本信息-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MatterInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editMatterInfo(@RequestBody MatterInfo matterInfo) {


        matterInfoService.updateByPk(matterInfo);

        return Result.ok("edit-ok", "修改成功！").setData(matterInfo);
    }

    @ApiOperation(value = "事项库-事项基本信息-批量修改某些字段", notes = "")
    @ApiEntityParams(value = MatterInfo.class, props = {}, remark = "事项库-事项基本信息", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = MatterInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        matterInfoService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "事项库-事项基本信息-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelMatterInfo(@RequestBody List<MatterInfo> matterInfos) {
        User user = LoginUtils.getCurrentUserInfo();
        if (matterInfos.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<MatterInfo> datasDb = matterInfoService.listByIds(matterInfos.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<MatterInfo> can = new ArrayList<>();
        List<MatterInfo> no = new ArrayList<>();
        for (MatterInfo data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            matterInfoService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "事项库-事项基本信息-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MatterInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(MatterInfo matterInfo) {
        MatterInfo data = (MatterInfo) matterInfoService.getById(matterInfo);
        return Result.ok().setData(data);
    }

}
